// JavaScript Document

const VERSION = "Version = 1.0.0";

var expiresDate = new Date();
expiresDate.setTime(expiresDate.getTime() + (30 * 60 * 1000));
//?替换成分钟数如果为60分钟则为 60 * 60 *1000
jQuery.cookie("__cookie__", 'helloworld', {
    path: '/', //cookie的作用域
    expires: expiresDate
});

function strTime(stamp){
    var msgTime = new Date(stamp);
    var strTime = msgTime.getFullYear().toString() + '-' +
        (msgTime.getMonth()+1).toString().padStart(2,'0') + '-' +
        msgTime.getDate().toString().padStart(2,'0') + ' ' + 
        msgTime.getHours().toString().padStart(2,'0') + ':' +
        msgTime.getMinutes().toString().padStart(2,'0') + ':' +
        msgTime.getSeconds().toString().padStart(2,'0');
    return strTime;
}

function loadpy(url, postInfo, callback, syn=true) {
    if (!arguments[3]) syn = true; 
    var fdata = new FormData();
    for (var key in postInfo) {
        fdata.append(key, postInfo[key]);
    }
    var xmlhttp = new XMLHttpRequest(); //暂时先不添加对ie6及以下的支持了
    //url = encodeURI(url);
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            if (callback) { //没有callback函数的话，就相当于只发送命令而不接收返回值
                callback(xmlhttp.responseText);
            }
        }
    };
    xmlhttp.open("POST", "" + url, syn);
    xmlhttp.send(fdata);
}

var defaultContent = {
    userInfo:{
        id:"unkown",
        nickname:"匿名用户",
        gender:"",
        avatar:0,
        otherinfo:{}
    },
    reg:{
        id:"",
        password:"",
        confirm:"",
        nickname:"",
        gender:"male",
        avatar:0,
        otherinfo:{}
    }
}

var imgArray = [...new Array(30).keys()];

//引用
const refContents = {
    data() {
        return {
            refCont:false
        }
    },
    props: ["doc"],
    template:`
        <div class="ref" @click="refCont=!refCont">
            [{{doc.index_id}}]&nbsp;{{doc.title}}
        </div>
        <div class="reftext" v-if="refCont">
            <strong>{{doc.doc_name}}</strong>
            <br>
            {{doc.text}}
        </div>
    `
};
const chatFrame = {
    props:["msg","uid"],
    compute:{
        isSelf(){
            return msg.usr.id == id;
        }
    },
    components:{
        refContents
    },
    template:`
        <div :class="isSelf?'chatselfs':'chatfriend">
            <img v-if="isSelf==false"
                alt="Avatar" 
                :src="'data/avatar/'+ msg.usr.avatar +'.jpg'" 
                class="circle" 
                style="height: 2em"> 
            <span :class="isSelf?'text-end':'text-start">
                <div class="title">{{msg.usr.nickname}}</div>
                <div :class="isSelf?'chartSelf':"chartOther">
                    <span v-html="msg.msg"></span> 
                    <template v-if="msg.ref">
                        <ref-contents v-for="refer in msg.ref" 
                        :doc="refer"></ref-contents>
                    </template>                                 
                </div>
                <div class="time">{{msg.cts}}</div>
            </span>
            
            <img v-if="isSelf"
                alt="Avatar" 
                :src="'data/avatar/'+ msg.usr.avatar +'.jpg'" 
                class="circle" 
                style="height: 2em"> 
        </div>
    `
}

var XiaoC = {id:"XiaoC",nickname:"小C",avatar:"1"}

const starmsg = Vue.createApp({
    name: "starmsg",
    data() {
        return {
            boardSelect: 0, //0聊天；1登陆；2注册；3登陆成功；4用户信息
            waiting:false,
            login: {
                id: jQuery.cookie("userid") == undefined ? "" : jQuery.cookie("userid"),
                psw: jQuery.cookie("userpsw") == undefined ? "" : jQuery.cookie("userpsw")
            },
            password:"",
            confirm:"",
            userInfo:{
                id:"",
                nickname:"",
                gender:"",
                avatar:0,
                otherinfo:""
            },
            tempInfo:{
                id:"",
                nickname:"",
                gender:"",
                avatar:0,
                otherinfo:""
            },
            reg:{
                id:"",
                password:"",
                confirm:"",
                nickname:"",
                gender:"male",
                avatar:0,
                otherinfo:""
            },
            imgs:imgArray,
            textScnContent:"",
            allUsers:[XiaoC],
            usrOnline:[],
            usrSelect:"XiaoC",
            usrAlert:[],
            inputMsg:"",
            msgScreen:[{
                usr:XiaoC,
                msg:"你好，我是研究助手小C，欢迎和我交流！",
                ref:'ERROR',
                cts:strTime(new Date())
            }]
        }
    },
    methods: {
        compare(a,b){
            return a==b;
        },
        renderMarkdown(input){
            return marked.parse(input.replaceAll("\\",'$@$').replaceAll("_",'$+$'))
                .replaceAll("$@$","\\").replaceAll("$+$","_")
        },
        userlogin() {
            jQuery.cookie("userid", this.login.id);
            jQuery.cookie("userpsw", this.login.psw);
            loadpy('login',{
                id: this.login.id,
                psw: this.login.psw
            },(resp)=>{
                result = JSON.parse(resp);
                if (result.check) {
                    var usrInfo = result.info;
                    textScreen("欢迎回来，" + usrInfo.nickname + "!");
                    this.userInfo = usrInfo;
                    this.boardSelect = 3;
                } else {
                    alert("用户名密码错误");
                }                
            });
        },
        usrstat(uid){
            if(uid == this.usrSelect){
                return 0;
            }
            if(this.usrOnline.indexOf(uid)!=-1){
                return 1;
            }
            return 2;
        },
        logout(){
            this.boardSelect = 0;
            this.userInfo = defaultContent.userInfo;
        },
        userRegister(){
            if(!this.reg.id){
                alert('id不能为空');
                return;
            }
            if(!this.reg.password){
                alert('密码不能为空');
                return;
            }
            if(!this.reg.nickname){
                alert('昵称不能为空');
                return;
            }
            if(this.reg.nickname.length>10){
                alert('昵称不能大于10个字符');
            }
            if(this.reg.password != this.reg.confirm){
                alert('两次输入的密码不同！');
                return;
            }
            loadpy('register',this.reg,(resp)=>{
                result = JSON.parse(resp);
                if (result.check) {
                    this.login.id = this.reg.id;
                    this.login.psw = this.reg.password;
                    this.userlogin();
                    this.reg = defaultContent.reg;
                } else {
                    alert(result.info);
                }               
            });            
        },
        userUpdate(){
            if(!this.userInfo.nickname){
                alert('昵称不能为空');
                return;
            }
            if(this.userInfo.nickname.length>10){
                alert('昵称不能大于10个字符');
                return;
            }
            loadpy('update',this.tempInfo,(resp)=>{
                result = JSON.parse(resp);
                if (result.check) {
                    textScreen("修改成功！");
                    this.usrInfo = result.info;
                }             
            });              
            this.userInfo = this.tempInfo;
        },
        changePassword(){
            if(!this.password){
                alert('密码不能为空');
                return;
            }
            if(this.password != this.confirm){
                alert('两次输入的密码不同！');
                return;
            }
            loadpy('password',{
                id:this.tempInfo.id,
                password:this.password
            },(resp)=>{
                result = JSON.parse(resp);
                if (result.check) {
                    textScreen("修改成功！");
                    this.usrInfo = result.info;
                }             
            });       
        },
        sendMessage(){
            if(!this.inputMsg){
                return
            }
            this.waiting = true;
            this.msgScreen.push({
                usr:{
                    id:this.userInfo.id,
                    nickname:this.userInfo.nickname,
                    avatar:this.userInfo.avatar
                },
                msg:this.inputMsg,
                cts:strTime(new Date()),
                ref:'ERROR'
            });
            setTimeout(()=>{
                document.getElementById('chartWindow').scrollTop = document.getElementById('chartWindow').scrollHeight;
                document.getElementById('chartWindowM').scrollTop = document.getElementById('chartWindowM').scrollHeight;    
            },100);   
            loadpy('sendMessage',{
                id1: this.userInfo.id,
                id2: "XiaoC",
                msg: this.inputMsg,
                ref: ""  
            },(resp)=>{
                var res = JSON.parse(resp);
                var refs = JSON.parse(res.ref)
                
                this.msgScreen.push({
                    usr:res.usr,
                    msg:res.msg,
                    ref:refs!=null? refs:'ERROR',
                    cts:strTime(res.cts)});
                this.waiting = false;
                setTimeout(()=>{
                    document.getElementById('chartWindow').scrollTop = document.getElementById('chartWindow').scrollHeight;
                    document.getElementById('chartWindowM').scrollTop = document.getElementById('chartWindowM').scrollHeight;    
                },100);        
            });            

            this.inputMsg="";
        },
        getMessage(){
            this.waiting=true;
            loadpy('getMessage',{
                id1: this.userInfo.id,
                id2: "XiaoC",
                num:300
            },(resp)=>{
                result = JSON.parse(resp);
                this.msgScreen = [];
                result.forEach((res)=>{
                    if(res[0]=='XiaoC') usr=XiaoC;
                    else usr=this.userInfo;
                    this.msgScreen.push({
                        usr:usr,
                        msg:res[1],
                        cts:strTime(res[2]),
                        ref:res[3] != "" && res[3] != "null" ? JSON.parse(res[3]) : 'ERROR',
                    });
                });
                this.waiting=false;
                setTimeout(()=>{
                    document.getElementById('chartWindow').scrollTop = document.getElementById('chartWindow').scrollHeight;
                    document.getElementById('chartWindowM').scrollTop = document.getElementById('chartWindowM').scrollHeight;    
                },100);        
            });  
        },
        textScn(str){
            this.textScnContent += str+"<br>";
            setTimeout(()=>{
                document.getElementById('message1').scrollTop = document.getElementById('message1').scrollHeight;
                document.getElementById('message2').scrollTop = document.getElementById('message2').scrollHeight;    
            },100);
        },
        autologin(){
            if(this.login.id && this.login.psw){
                this.userlogin();
            }
        }
    },
    components:{
        refContents,
        chatFrame
    },
    mounted() {
        window.textScreen = this.textScn;
        window.sendmsg = this.sendMessage;
        this.autologin();

        if (isMathjaxConfig) {
          // 判断是否初始配置，若⽆则配置。
            initMathjaxConfig()
        }
        TypeSet()
  },
  updated() {
    if (isMathjaxConfig) {
      // 判断是否初始配置，若⽆则配置。
      initMathjaxConfig()
    }
    TypeSet()
  }

});
var textScreen;
var sendmsg;

//////////////////////////////////////////////////////////////////////////////////
jQuery(document).ready(function () {

    starmsg.mount("#starmsg");
    textScreen(VERSION);

    var latestVersion = jQuery("#version").html();
    if (latestVersion != VERSION) {
        textScreen("最新版本为" + latestVersion + ",请按ctrl+F5重新加载！");
    }

    jQuery("#textBox").bind('keyup', function (event) {
        if (event.keyCode == '13') {
            sendmsg();
        }
    });
    jQuery("#textBoxM").bind('keyup', function (event) {
        if (event.keyCode == '13') {
            sendmsg();
        }
    });

    jQuery("#chartWindow").css('height', window.innerHeight / 1.3 + 'px');
    window.onresize = () => {
        jQuery("#chartWindow").css('height', window.innerHeight / 1.3 + 'px');
    }
    jQuery("#chartWindowM").css('height', window.innerHeight / 2 + 'px');
    window.onresize = () => {
        jQuery("#chartWindowM").css('height', window.innerHeight / 2 + 'px');
    }
});
